package com.egg.gateway.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.egg.common.core.constant.StringPool;
import com.egg.common.util.IpUtil;
import com.egg.gateway.constant.FilterOrderConstant;
import com.egg.gateway.constants.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Profile;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author east
 */
@Profile({"test", "dev", "local"})
@Slf4j
@Component
public class LogFilter implements GlobalFilter, Ordered {


    /**
     * 耗费时长KEY
     */
    private static final String SPEND_TIME = GatewayConstant.SYSTEM_NAME + StringPool.UNDERSCORE + "spend_time";

    @Override
    public int getOrder() {
        return FilterOrderConstant.LOG_FILTER_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ContextFilter.GatewayContext gatewayContext = exchange.getAttribute(ContextFilter.GatewayContext.CACHE_GATEWAY_CONTEXT);
        String param = "";
        if (null != gatewayContext) {
            param = gatewayContext.getParameter();
        }
        String finalParam = param;
        exchange.getAttributes().put(SPEND_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long start = exchange.getAttribute(SPEND_TIME);
            if (ObjectUtil.isNotEmpty(start)) {
                Long end = System.currentTimeMillis() - start;
                //设置上下文
                StringBuilder from = new StringBuilder();
                from.append("IP: ").append(IpUtil.requestIp(request)).append("\n")
                        .append("请求头: ").append(JSON.toJSONString(request.getHeaders())).append("\n")
                        .append("接口类型: ").append(request.getMethodValue()).append("\n")
                        .append("服务器: ").append(request.getURI().getAuthority()).append("\n")
                        .append("路径: ").append(request.getURI().getPath()).append("\n")
                        .append("参数: ").append(finalParam).append("\n")
                        .append("耗时: ").append(end).append("ms").append("\n")
                ;
                log.debug("请求日志: {}", from.toString());
            }
        }));
    }


}